<template>
  <el-dialog :title='detail.id ? "修改角色" :"添加角色"' :visible.sync="dialogVisible">
    <el-form ref="detailForm" :model="detail"
             :rules="rules" label-width="80px" size="small">
      <el-row>
        <el-col :span="12">
          <el-form-item label="角色名称" prop="roleName">
            <el-input :disabled="readonly" v-model="detail.roleName" placeholder="角色名称"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注">
            <el-input :disabled="readonly" v-model="detail.remark" placeholder="角色描述"/>
          </el-form-item>
        </el-col>

        <el-col class="role-menu-list" :span="24" style="padding:15px 0 30px 12px">
          <div style="border-bottom: 1px solid #ccc;;padding-bottom: 5px;color: #027BE3">权限资源</div>
          <div style="margin-top: -30px;margin-left: -30px;padding-top: 10px;">
            <div v-for="item in allMenus" :key="item.id" class="menu-tree">
              <el-tree
                show-checkbox
                :default-expanded-keys="exportList"
                :default-checked-keys="checkMenus"
                :ref="`menu-${item.id}`"
                :data="[item]"
                node-key="id">
              </el-tree>
            </div>
          </div>
        </el-col>
      </el-row>
      <el-form-item class="from-bnts">
        <el-button @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" :loading="loading" @click="saveRole">保存</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script>
  import utils from '@/assets/utils/zhzf-util';
  import roleApi from "@/api/system/role";
  import menuApi from "@/api/system/menu";
  import TreeSelect from "../../comps/zhzf/tree-select";

  export default {
    name: "roleDetail",
    components: {TreeSelect},
    data() {
      return {
        readonly: false,
        loading: false,
        dialogVisible: false,
        allMenus: [],
        checkMenus: [],
        exportList: [],
        // 表单校验
        rules: {
          roleName: [
            {
              required: true,
              message: '角色名称不能为空',
              trigger: 'blur'
            }
          ]
        },
        detail: {},
      };
    },
    methods: {
      initPage(detail, readonly) {
        this.readonly = readonly;
        this.detail = detail || {};
        this.dialogVisible = true;
        this.loadMenuTree();
      },
      /**
       * 查询权限资源树
       * 1、根据用户权限查询权限列表
       * 2、根据当前角色查询管理的权限列表
       * 3、反选角色权限节点
       */
      async loadMenuTree() {
        let res = await menuApi.list({pageSize: Number.MAX_SAFE_INTEGER});
        let menuTree = utils.generatorDeptTree(res.data, this.readonly);
        this.allMenus = menuTree.treeList;

        //展开1级菜单
        this.allMenus.forEach(item => {
          this.exportList.push(item.id)
        })


        //查询角色菜单设置反选
        this.checkMenus = [];
        if (this.detail.id) {
          res = await roleApi.roleMenu({id: this.detail.id});
          let roleMenus = res.data;
          roleMenus.forEach(item => {
            this.checkMenus.push(item.id);
          })
        }
      },
      saveRole() {
        this.$refs.detailForm.validate(async valid => {
          if (!valid) {
            return;
          }
          let menuIds = [];
          this.allMenus.forEach(item => {
            menuIds.push(...this.$refs[`menu-${item.id}`][0].getCheckedKeys(true));
          });
          if (!menuIds.length) {
            utils.showTips('请选择角色权限资源', false);
            return;
          }

          this.detail.roleKey = this.detail.roleName;
          let method = this.detail.id ? roleApi.modRole : roleApi.addRole;
          this.loading = true;

          let submitData = {role: this.detail, roleDepts: [], roleMenus: []};
          menuIds.forEach(item => {
            submitData.roleMenus.push({menuId: item, roleId: this.detail.id});
          })
          let res = await method(submitData);
          if (res.ok) {
            this.dialogVisible = false;
            this.$emit("submit");
          }
          utils.showTips(`角色信息编辑${res.ok ? '成功' : '失败'}`, res.ok);
          this.loading = false;
        });
      },
    }
  };
</script>

<style lang="scss">
  .role-menu-list {
    .menu-tree {
      display: inline-table;
      padding-top: 30px;
      padding-left: 30px;
      min-width: 150px;
    }
  }
</style>
